package com.voodoo.lib_frame.view;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.support.annotation.Nullable;
import android.util.AttributeSet;
import android.util.TypedValue;

import com.voodoo.lib_frame.R;
import com.voodoo.lib_utils.L;

/**
 * Author: voodoo
 * CreateDate: 2020/05/06 006 01:45 下午
 * Description: 根据文本内容自动调整字体大小
 */
public class AutofitTextView extends android.support.v7.widget.AppCompatTextView {

    private float mDefaultTextSize;
    private Paint mTextPaint;
    private int minTextSize = 10; // 最小文字大小

    public AutofitTextView(Context context) {
        this(context, null);
    }

    private void initAttr() {
        mTextPaint = new Paint();
        mTextPaint.set(getPaint());
        mDefaultTextSize = getTextSize();
    }

    public AutofitTextView(Context context, @Nullable AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public AutofitTextView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        initAttr();
    }

    @Override
    protected void onTextChanged(CharSequence text, int start, int lengthBefore, int lengthAfter) {
        super.onTextChanged(text, start, lengthBefore, lengthAfter);
        refitText(text.toString(), getWidth());
    }

    @Override
    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
        super.onSizeChanged(w, h, oldw, oldh);
        refitText(getText().toString(), getWidth());
    }

    public void refitText(String text, int textViewWidth) {
//        L.iTag("refitText", "展示的文字:" + text, "TextView宽度:" + textViewWidth);
        if (textViewWidth > 0) {
            // 1、计算展示区域的宽度
            int availableTextWidth = textViewWidth - getPaddingLeft() - getPaddingRight();

            // 2、默认文字大小（xml中设置的TextSize）并将其先设置上
            float currentTextSize = mDefaultTextSize;
            mTextPaint.setTextSize(currentTextSize);

            // 3、获取String的绘制宽度
            float stringWidth = mTextPaint.measureText(text);

            // 4、如果string的绘制宽度大于展示区域的宽度
            while (stringWidth > availableTextWidth) {
                currentTextSize--;
                if (currentTextSize <= minTextSize) {
                    currentTextSize = minTextSize;
                    break;
                }
                mTextPaint.setTextSize(currentTextSize);
                stringWidth = mTextPaint.measureText(text);
            }
            setTextSize(TypedValue.COMPLEX_UNIT_PX, currentTextSize);
            invalidate();
        }
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
    }

}